package com.dl.mall.config.satoken;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.strategy.SaStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author DL
 * @create 2022-04-07 13:27
 */
@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    // Sa-Token 整合 jwt
/*    @Bean
    public StpLogic getStpLogicJwt() {
        // Style 模式：Token 风格替换
        return new StpLogicJwtForStyle();

        // Mix 模式：混入部分逻辑
        //return new StpLogicJwtForMix();

        // Stateless 模式：服务器完全无状态
        //return new StpLogicJwtForStateless();
    }*/

    // 注册Sa-Token的注解拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");

        // 注册路由拦截器，自定义认证规则
        registry.addInterceptor(new SaRouteInterceptor((req, res, handler)->{
            HttpServletRequest request = (HttpServletRequest) req.getSource();
            System.out.println("=========路由拦截开始=========");
            String uri = request.getRequestURI();//获取请求信息
            String queryString = request.getQueryString();//获取请求参数
            String referer = request.getHeader("referer");//请求的来源
            if (queryString == null){
                System.out.println("本次请求由  " + referer + "  ==>  " + uri + "  ");
            }else {
                System.out.println("本次请求由  " + referer + "  ==>  " + uri + "?" + queryString);
            }

            if (StpUserUtil.isLogin()){
                log.info("front -> isLogin:{}，getLoginId:{}", StpUserUtil.isLogin(), StpUserUtil.getLoginId());
            }
            if (StpAdminUtil.isLogin()){
                log.info("admin -> isLogin:{}，getLoginId:{}", StpAdminUtil.isLogin(), StpAdminUtil.getLoginId());
                log.info("admin -> StpAdminUtil.getTokenInfo:{}", StpAdminUtil.getTokenInfo());
            }

            // 登录认证 -- 拦截所有路由，并排除/user/doLogin 用于开放登录
            //SaRouter.match("/admin/**", r -> StpAdminUtil.checkLogin());

            // 权限认证 -- 不同模块认证不同权限
            System.out.println("=========路由拦截结束=========");
        })).addPathPatterns("/**");

    }

    @Autowired
    public void rewriteSaStrategy() {
        // 重写Sa-Token的注解处理器，增加注解合并功能
        SaStrategy.me.getAnnotation = AnnotatedElementUtils::getMergedAnnotation;
    }
}

